<template>
    <el-dialog
      class="nodeDialog custom-dialog"
      v-model="dialogVisible"
      width="900"
      :show-close='false'
      modal-class="dialog-center"
    >
      <div class="custom-dialog-header">
        <div class="title-box">
            <div class="title">{{$t('message.text.notes')}}</div>
        </div>
        <svg class="close-icon" @click="cancel">
            <use xlink:href="#keowledge-danchuangguanbi1"></use>
        </svg>
      </div>
      <link rel="stylesheet" href="./jf-ui-public/cdn/editor.md/css/editormd.css"/>
      <div id="editor" class="editor-box" style="z-index: 10" v-if="!mdIsPreview && dialogVisible">
      </div>
      <div id="editorPreview" class="editor-box" v-if="mdIsPreview && dialogVisible">
        <textarea id="append-test" style="display:none;">{{content}}</textarea>
      </div>
      <template #footer>
        <span class="dialog-footer" v-if="!mdIsPreview">
          <el-button @click="cancel">{{$t('message.buttons.cancal')}}</el-button>
          <el-button type="primary" @click="confirm">{{$t('message.buttons.submit')}}</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  nextTick,
  getCurrentInstance
} from 'vue' 
import type {ComponentInternalInstance} from 'vue'
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
import initPasteDragImg from '@/components/editorMd/uploadImg'
import scriptjs from 'scriptjs'
import useUserInfoStore from '@/store/userInfo';
import { useRouter } from "vue-router"
const router = useRouter();
const userStore = useUserInfoStore()
const emit = defineEmits([""])
const props = defineProps({
  docInfo:{
    type:Object,
    default(){
      return {}
    }
  }
})

const dialogVisible = ref(false)
const content = ref('')
const activeNodes = ref([])
const editor = ref(null)
const mdIsPreview = ref(false)
const height = ref('calc(100vh - 250px)')
onMounted(()=>{
  proxy.$eventBus.$on("node_active", (...args) => {
    activeNodes.value = args[1];
    if (activeNodes.value.length > 0) {
      let firstNode = activeNodes.value[0];
      content.value = firstNode.getData("note");
    } else {
      content.value = "";
    }
  });
  proxy.$eventBus.$on("showNodeNote", (value,note) => {
    mdIsPreview.value = value
    proxy.$eventBus.$emit('startTextEdit');
    dialogVisible.value = true;
    nextTick(() => {
      if(!value){
        let firstNode = activeNodes.value[0];
        content.value = firstNode.getData("note");
        setInit();
      }else{
        setInit();
      }
    });
  });
})

async function  setInit(){
  await fetchScript('/jf-ui-public/cdn/editor.md/editormd.js')
  // await this.fetchScript('/jf-ui-public/cdn/editor.md/editormd.amd.js')
  if(locale.value.indexOf('zh')==-1){
    await fetchScript('/jf-ui-public/cdn/editor.md/languages/en.js')
  }
  if(mdIsPreview.value){
    await fetchScript('/jf-ui-public/cdn/editor.md/lib/marked.min.js')
    await fetchScript('/jf-ui-public/cdn/editor.md/lib/prettify.min.js')
    await fetchScript('/jf-ui-public/cdn/editor.md/lib/raphael.min.js')
    await fetchScript('/jf-ui-public/cdn/editor.md/lib/sequence-diagram.min.js')
    await fetchScript('/jf-ui-public/cdn/editor.md/lib/flowchart.min.js')
  }
  nextTick(() => {
    // 内容
    if(!mdIsPreview.value){
      editor.value = window.editormd('editor', {
        path: '/jf-ui-public/cdn/editor.md/lib/',
        placeholder: $t('message.placeholder.markdown'),
        height: height.value,
        emoji: true,
        // 工具栏
        toolbarIcons:['undo','redo','|','bold','del','italic','quote','ucwords','uppercase','lowercase','|','h1','h2','h3','h4','h5','h6','|','list-ul','list-ol','hr',
        '|','link','reference-link','image','code','preformatted-text','code-block','table','datetime','emoji','html-entities','pagebreak','|','goto-line','watch',
        'preview','fullscreen','clear','search','help'],
        // 开启图片上传，图片上传重写了的
        saveHTMLToTextarea: true,
        // 可分区域定制样式主题
        theme        : "default",
        editorTheme  : "default",
        previewTheme : "default",
        imageUpload: true,
        imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp","ico"],
        lang:{
          name: locale.value.indexOf('zh')!=-1?"zh-cn":'en',
        },
        reqData:{

        },
        headers:{
          businessId:props.docInfo.id,
          Authorization: 'Bearer ' + userStore.access_token
        },
        //需在服务端定义接口
        // 这里需要考虑返回值，所以封装了一层
        imageUploadURL: '#',
        custImageUploadUrl:'/mgr/jvs-auth/upload/jvs-public',
        htmlDecode: true, // 识别html标签
        onpreviewing : function() {
          // 这里只是预览
        },
        onpreviewed : function() {
          // 这里是编辑加预览
        },
        // 监听更新，更新父组件值
        onchange: function() {
          // console.log("111")
          // 获取当前页面的的光标位置
          // console.log(editor.getCursor())
        },
        // 退出全屏
        onfullscreen: function() {
          // 原生JS修改层级
          var editor = document.getElementById('editor')
          editor.style['z-index'] = 13
        },
        // 全屏
        onfullscreenExit: function() {
          // 原生JS修改层级
          var editor = document.getElementById('editor')
          editor.style['z-index'] = 10
        },
        // 大小改变
        onresize : function() {
        },
        // 加载完成后再设置内容
        onload: function() {
          this.setMarkdown(content.value)
          initPasteDragImg(this)
        }
      })
    }else{
      editor.value = window.editormd.markdownToHTML("editorPreview", {
        htmlDecode      : "style,script,iframe",  // you can filter tags decode
        emoji           : true,
        taskList        : true,
        tex             : true,  // 默认不解析
        sequenceDiagram : true,  // 默认不解析
      });
    }
  })
}
function fetchScript(url) {
  return new Promise((resolve) => {
    scriptjs(url, () => {
      resolve()
    })
  })
}
function cancel() {
  dialogVisible.value = false;
}
function confirm() {
  console.log(editor.value)

  content.value = editor.value.getMarkdown();
  activeNodes.value.forEach((node) => {
    node.setNote(content.value);
  });
  cancel();
}

</script>
<style scoped lang="scss">
::v-deep(.nodeDialog){
  .el-dialog__body{
    height: 50vh;
  }
}
</style>
